#!/bin/bash
#
# Copyright 2006 Kaio Rafael de Souza Barbosa
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# ---------------------------------------------------------
# Este script cria repositorio, muda a permissao para o apache
# poder ler e escrever os commits realizados pelos usuarios
#
# Para mais detalhes do subversion acesse: 
# http://svnbook.red-bean.com/nightly/pt_BR/svn-book.html#svn.serverconfig.httpd
# http://svnbook.red-bean.com/nightly/pt_BR/svn-book.html#svn.reposadmin


# Variables

apache_user=www-data # usuario do apache
apache_group=www-data # grupo do usuario do apache
apache_htpass_cmd=/usr/bin/htpasswd2 # comando do apache
svn_root_home=/home/kaio/web-svn # diretorio que armazena todos os repositorios do subversion
svn_adm_cmd=/usr/bin/svnadmin # comando do svnadmin
svn_pass=/etc/apache2/senha # arquivo de senha dos usuarios do subversion
svn_access_file=/etc/apache2/projetos # diretorio com as permissoes do subversion
svn_tmp=/tmp/repos # arquivo temporario
svn_web_page=/svn # endereco web que ficara o repositorio http://server/svn/nome_repositorio
nome_empresa="Free Software Foundation" # Nome da sua empresa
auto_passwd=`od /dev/urandom | head -1 | awk '{print $2}'` # senha gerada pelo /dev/random
#auto_passwd=`mkpasswd *3$%#er` # senha gerada pelo mkpasswd

# Functions

usage(){
	echo "$(basename $0) opcoes"
	echo "Opcoes"
	echo "--create		: Cria um repositorio"
	echo "--adduser user		: Adiciona um usuario"
	echo "--adduser-gen user	: Mesmo que --adduser, porem o sistema gera uma senha"
	echo "--help			: Imprime esta ajuda"
}

create_svn(){
	echo -n "Entre com o nome do repositorio a ser criado: "
	read svn_repos

	# verifica se o repositorio ja existe

	if [ -d ${svn_root_home}/${svn_repos} ];then
		echo "Repositorio ${svn_repos} ja existe"
		exit 1

		else

		if `${svn_adm_cmd} create ${svn_root_home}/${svn_repos}` ; then
			echo "Repositorio ${svn_repos}, criado com sucesso!!"
			else
			echo "Erro na criacao do repositorio  ${svn_repos}"
			exit 1
		fi
	fi
# Mudando as permissoes de dav lock e db

echo "Mudando as permissoes de dav, lock e db"

chmod g+w  ${svn_root_home}/${svn_repos}/dav  ${svn_root_home}/${svn_repos}/locks  ${svn_root_home}/${svn_repos}/db
chmod g+s  ${svn_root_home}/${svn_repos}/dav  ${svn_root_home}/${svn_repos}/locks  ${svn_root_home}/${svn_repos}/db

chown -R ${apache_user}:${apache_group} ${svn_root_home}/${svn_repos}/dav
chown -R ${apache_user}:${apache_group} ${svn_root_home}/${svn_repos}/locks
chown -R ${apache_user}:${apache_group} ${svn_root_home}/${svn_repos}/db

touch ${svn_access_file}/${svn_repos}

sleep 1

# Imprimindo a saida para o Apache
cat << EOF > $svn_tmp
###########################
#   Projeto ${svn_repos}
###########################
<Location ${svn_web_page}/${svn_repos}>
   DAV svn
   SVNPath ${svn_root_home}/${svn_repos}
   AuthType Basic
   AuthName "${svn_repos} em ${nome_empresa} "
   AuthUserFile ${svn_pass}
   AuthzSVNAccessFile ${svn_access_file}/${svn_repos}
   Require valid-user
   Allow from all
</Location>
EOF

echo "Adicione as linhas abaixo no arquivo do apache"
echo " "
cat  $svn_tmp


}

# Funcao Adicionar Usuario 
adduser_svn(){
	if [ -z $1 ]; then
		echo "Digite o nome do usuario"

 	elif [ "$(cut -f1 -d: ${svn_pass} | grep $1)" = $1 ]; then
		echo "Usuario $1, ja existe"
		else
		echo "Criando usuario: $1"
		${apache_htpass_cmd} ${svn_pass} $1
	fi

}

# Funcao adduser com senha gerada
adduser_genpass(){
	if [ -z $1 ]; then
                echo "Digite o nome do usuario"

        elif [ "$(cut -f1 -d: ${svn_pass} | grep $1)" = $1 ]; then
                echo "Usuario $1, ja existe"
                else
                echo "Criando usuario: $1"
                ${apache_htpass_cmd} -b ${svn_pass} $1 ${auto_passwd}
		echo "A Senha para: $1 e':  ${auto_passwd}"
        fi
}


# Main Program

# Validando as variaveis de sistema

if [ ! -f ${svn_pass} ];then
	echo 
	echo "O arquivo:  ${svn_pass} nao existe"
	echo "Voce deve mudar a variavel \${svn_pass}"
	echo 
	exit 1
fi

if [ ! -d ${svn_access_file} ] ;then
	echo 
	echo "O diretorio: ${svn_access_file} nao existe"
	echo "Voce deve mudar a variavel \${svn_access_file}"
	echo 
	exit 1
fi


if [ $(id -u) -eq 0 ];then
	if [ $# -eq 0 ]; then
		usage
		else
		case $1 in 
		--create) create_svn;;
		--adduser) adduser_svn $2;;
		--adduser-gen) adduser_genpass $2;;
		--help) usage;;
		*) echo "Parametro $1, desconhecido";;
		esac
	fi
	else
	echo "Voce nao e' o root"
	exit 1
fi
